# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-07-10
# @File : 6_complete_autologin.py

import time
import uuid
import json
import hashlib
import base64

import rsa
import requests


def md5(arg):
    ha = hashlib.md5()
    ha.update(arg.encode('utf-8'))
    return ha.hexdigest()


def encrypt(data_string):
    pub_key_str = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9G4LU8LZtxApKhP81Usk7ze7obk8osQQcHhVdEfVoVIL3PTd2oIknWBBdIQz/r7HCVeZr6kMaESFc6dpmLime06JWyg902I0S+e8UnAaXhIQJso4wBVD4KtRKozCZ4XzFg8xK40/jO3rJA7WU7Tsn2qcr+MYyqLnN31umo3zZZwIDAQAB\n-----END PUBLIC KEY-----\n'
    key = rsa.PublicKey.load_pkcs1_openssl_pem(pub_key_str.encode('utf-8'))
    rsa_bytes = rsa.encrypt(data_string.encode(encoding='utf-8'), key)
    b64_bytes = base64.b64encode(rsa_bytes)
    return b64_bytes.decode('utf-8')


def encrypt_password(data_string):
    data_list = []
    for char in data_string:
        data_list.append(encrypt(char))
    pwd_string = json.dumps(data_list)
    return pwd_string


def do_login(phone, password):
    # 请求头：version
    # 请求头：version
    version = "tgou_Android_V2.7.10.1"

    # 请求头：key
    data_string = f"{version}miyue"
    key = md5(data_string)

    # 请求头：tags_uuid
    tgs_uuid = str(uuid.uuid4())

    # 时间戳
    timestamp = int(time.time() * 1000)

    res = requests.post(
        url="https://mServ.51tiangou.com/app/member/login",
        data={
            "password": password,
            "cellPhone": phone,
        },
        headers={
            "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 10; Pixel 2 XL Build/QQ3A.200805.001)@tiangou/android/20221101/{}".format(
                timestamp),
            "version": version,
            "tgVersion": "@tiangou/android/20221101/{}".format(timestamp),
            "mid_version": "8",
            "mid_global": "android",
            "key": key,
            "tgs_uuid": tgs_uuid,
            "Host": "mServ.51tiangou.com",
        }
    )

    print(res.text)


def run():
    phone, password = "18378353331", "Qwer123456"

    phone = encrypt(phone)
    password = encrypt_password(password)

    do_login(phone, password)


if __name__ == '__main__':
    run()
